/**
 * 校准
 */

import { ConfigProvider, Input, message, Modal, Select, Spin } from "antd";
import { FC, useEffect, useState } from "react";
import {
  getKshCalibration,
  IKshCalibrationPrams,
  IKshGetWeight,
  postKshGetWeight,
} from "../../api";
import { useWindowFontSize } from "../../../../assets/fun/Antd/configprovider";
import {
  ButtonBox,
  JianzhunMoadlBox,
  JianzhunMoadlInputBox,
  JiaozhunInfoBox,
  JiaozhunInfoTitle,
  JiaozhunStatusActionBox,
  JisuanBox,
} from "./style";
import { ISelectList } from "../../../../type/antd";
import { handleGetDictionaryItem } from "../../../../assets/fun/DictionaryItem";
import chepai_select_bg from "../../../../assets/image/LaneMonitoring/chepai_select_bg.png";

const ModuleJiaozun: FC<{
  open: boolean;
  id: React.Key;
  geiliaoji: number;
  handleCallback: () => void;
}> = ({ open, id, geiliaoji, handleCallback }) => {
  const [carColorList, setCarColorList] = useState<ISelectList[]>([]); // 车辆类型字典项
  const [chepaiColor, setChepaiColor] = useState<string>(""); // 车牌颜色
  const [chepaihao, setchepaihao] = useState<string>(""); // 车牌号
  const [cheliangList, setcheliangList] = useState<IKshGetWeight[]>([]); // 车辆信息列表
  const [jiaozhunLoading, setjiaozhunLoading] = useState(false); // 校准加载中
  const [jiaozhunOk, setjiaozhunOk] = useState(false); // 校准成功
  const [jiaozhunErr, setjiaozhunErr] = useState(false); // 校准失败
  const [jiaozhunErrMsg, setjiaozhunErrMsg] = useState(""); // 校准失败信息

  useEffect(() => {
    let carArr = handleGetDictionaryItem("CPYS");
    let carArr1: ISelectList[] = [];
    carArr.forEach((element) => {
      carArr1.push({
        value: element.label,
        label: element.label,
      });
    });
    setChepaiColor(carArr1[0].value as string);
    setCarColorList(carArr1);
  }, []);

  const handleCancel = () => {
    setjiaozhunOk(false);
    setjiaozhunErr(false);
    setjiaozhunErrMsg("");
    setcheliangList([]);
    setchepaihao("");
    handleCallback();
  };
  // 查找
  const handleClickChazhao = async () => {
    if (chepaihao === "") {
      message.warning("请输入车牌号");
      return;
    }
    const { code, msg, data } = (await postKshGetWeight({
      carColor: chepaiColor,
      carNo: chepaihao,
    })) as { code: number; msg: string; data: IKshGetWeight[] };
    if (code === 20000) {
      message.success("查找成功");
      setcheliangList(data);
    } else {
      message.error(msg);
    }
  };
  // 进行校准
  const handleJiaozhun = async () => {
    const dibangValue = cheliangList.filter((item) => item.type === "地磅");
    const pidaichengValue = cheliangList.filter(
      (item) => item.type === "皮带秤"
    );
    setjiaozhunOk(false);
    setjiaozhunErr(false);
    setjiaozhunErrMsg("");
    setjiaozhunLoading(true);
    if (
      dibangValue.length === 0 ||
      pidaichengValue.length === 0 ||
      dibangValue[0].weight === undefined ||
      pidaichengValue[0].weight === undefined
    ) {
      message.warning("数据不完整，无法校准");
      setjiaozhunLoading(false);
      return;
    }
    const prams: IKshCalibrationPrams = {
      beltWeight: pidaichengValue[0].weight,
      scsWeight: dibangValue[0].weight,
      number: geiliaoji,
      id: id,
    };
    const { code, msg } = (await getKshCalibration(prams)) as {
      code: number;
      msg: string;
    };
    if (code === 20000) {
      message.success("校准成功");
      setjiaozhunOk(true);
      setjiaozhunErr(false);
    } else {
      setjiaozhunErr(true);
      setjiaozhunOk(false);
      setjiaozhunErrMsg(msg);
    }
    setjiaozhunLoading(false);
  };
  return (
    <ConfigProvider
      theme={{
        components: {
          Select: {
            optionSelectedColor: "#5697CC",
            colorText: "#5697CC",
            colorTextPlaceholder: "#5697CC",
            controlHeight: useWindowFontSize(44),
            selectorBg: ` url(${chepai_select_bg}) no-repeat 0 0 / 100% 100%`,
            lineWidth: 0,
          },
          Input: {
            lineWidth: 0,
            controlHeight: useWindowFontSize(44),
            colorText: "#5697CC",
          },
          Spin: {
            dotSize: useWindowFontSize(18),
          },
        },
      }}
    >
      <Modal
        title="皮带秤校准"
        closable={{ "aria-label": "Custom Close Button" }}
        open={open}
        className="jiaozun"
        getContainer={false}
        onCancel={handleCancel}
        footer={[
          <ButtonBox
            // onMouseDown={() => handleClick("b19", true)}
            // onMouseUp={() => handleClick("b19", false)}
            onClick={() => handleCancel()}
          >
            关闭
          </ButtonBox>,
        ]}
        width={useWindowFontSize(920)}
      >
        <JianzhunMoadlBox>
          <JianzhunMoadlInputBox>
            <div className="jiaozunMoadlInputBox_left">
              <span className="jiaozunMoadlInputBox_left_span">车牌号:</span>
              <Select
                value={chepaiColor}
                onChange={(value) => setChepaiColor(value)}
                options={carColorList}
                style={{ left: ".3rem" }}
              />
              <Input
                placeholder="请输入车牌号"
                value={chepaihao}
                onChange={(e) => setchepaihao(e.target.value)}
              />
              <div className="button_box" onClick={() => handleClickChazhao()}>
                <span className="iconfont">&#xe605;</span>
                <span>查找</span>
              </div>
            </div>
            <div
              className="btn"
              // onMouseDown={() => handleClick("b19", true)}
              // onMouseUp={() => handleClick("b19", false)}
              onClick={() => handleClickChazhao()}
            >
              <span className="iconfont">&#xe67d;</span> 刷新
            </div>
          </JianzhunMoadlInputBox>
          <JiaozhunInfoBox>
            <JiaozhunInfoTitle>
              <div className="message_icon_box"></div>
              <span>校准信息</span>
            </JiaozhunInfoTitle>
            <div className="table_box">
              <table>
                <thead>
                  <tr>
                    <th>类型</th>
                    <th>时间</th>
                    <th>重量</th>
                  </tr>
                </thead>
                <tbody>
                  {cheliangList.map((item, index) => (
                    <tr key={index}>
                      <td>{item.type}</td>
                      <td>{item.time}</td>
                      <td>{item.weight}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <JiaozhunInfoTitle>
              <div className="jisuanqi_icon_box"></div>
              <span>误差计算</span>
            </JiaozhunInfoTitle>
            <JisuanBox>
              <div className="gongsi">
                [（皮带秤下料值 - 车辆净重）÷车辆净重] × 100% = 校准误差值
              </div>
              <div className="zhushi_box">
                误差＞±0.5%需进行计量系数修正，将皮带秤设置为与车辆净重一致.
              </div>
              <JiaozhunStatusActionBox>
                {!jiaozhunLoading && !jiaozhunOk && !jiaozhunErr && (
                  <div className="text"></div>
                )}
                {jiaozhunLoading && (
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <Spin />
                    <span className="spin_text">校准中</span>
                  </div>
                )}
                {jiaozhunOk && (
                  <div className="status_success_box">
                    <span className="iconfont">&#xe6aa;</span>
                    <span>校准完成</span>
                  </div>
                )}
                {jiaozhunErr && (
                  <div className="status_error_box">
                    <span className="iconfont">&#xe6ac;</span>
                    <span>校准失败;{jiaozhunErrMsg}</span>
                  </div>
                )}

                <div
                  className="btn"
                  // onMouseDown={() => handleClick("b19", true)}
                  // onMouseUp={() => handleClick("b19", false)}
                  style={{ width: "14.8rem", color: "#92B2D0" }}
                  onClick={() => handleJiaozhun()}
                >
                  <span className="iconfont">&#xe635;</span> 执行计量修正
                </div>
              </JiaozhunStatusActionBox>
            </JisuanBox>
          </JiaozhunInfoBox>
        </JianzhunMoadlBox>
      </Modal>
    </ConfigProvider>
  );
};

export default ModuleJiaozun;
